import os
import sys

# 25.3
ssh_format = (
    '{SessionName} ({UserName}) = #109#0%{Host}%{Port}%{UserName}%%-1%-1%%%%%0%0%0%%%-1%-1%0%0%%1080%%0%0%1%%0%%%%0%-1%-1%0%%#MobaFont%{FontSize}%0%0%-1%15%236,236,236%30,30,30%180,180,192%0%-1%0%%xterm%-1%0%_Std_Colors_0_%80%24%0%1%-1%<none>%%0%0%-1%0%#0# #-1'
)

telnet_format = (
    '{SessionName} ({UserName}) = #98#1%{Host}%{Port}%{UserName}%%2%%%%%0%0%%1080%%%0%-1%0#MobaFont%{FontSize}%0%0%-1%15%236,236,236%30,30,30%180,180,192%0%-1%0%%xterm%-1%0%_Std_Colors_0_%80%24%0%1%-1%<none>%%0%0%-1%0%#0# #-1'
)


def read_file(xshell_session_file) -> list[str]:
    try:
        with open(xshell_session_file, 'r', encoding='utf-8') as f:
            return f.readlines()
    except:
        with open(xshell_session_file, 'r', encoding='utf-16') as f:
            return f.readlines()


def parse_xsh(xshell_session_file):
    session_lines = read_file(xshell_session_file)
    attrs = {}
    attrs['SessionName'] = os.path.basename(xshell_session_file).rsplit('.', 1)[0]

    for line in session_lines:
        if line.startswith('UserName='):
            attrs['UserName'] = line.split('=')[1].strip('\n')
        elif line.startswith('Port='):
            attrs['Port'] = line.split('=')[1].strip('\n')
        elif line.startswith('FontSize='):
            attrs['FontSize'] = line.split('=')[1].strip('\n')
        elif line.startswith('Host='):
            attrs['Host'] = line.split('=')[1].strip('\n')
        elif line.startswith('Protocol='):
            attrs['Protocol'] = line.split('=')[1].strip('\n')
        elif line.startswith('BaudRate='):
            attrs['Speed'] = line.split('=')[1].strip('\n')
    return attrs


def write_body(xshell_session_file, writer):
    attrs = parse_xsh(xshell_session_file)
    content = ""
    if attrs.get('Protocol').lower().startswith('ssh'):
        content = ssh_format.format(
            SessionName=attrs.get('SessionName') or 'default',
            UserName=attrs.get('UserName') or '',
            Port=attrs.get('Port') or '22',
            FontSize=attrs.get('FontSize') or '12',
            Host=attrs.get('Host') or '',
        )
    elif attrs.get('Protocol').lower() == 'telnet':
        content = telnet_format.format(
            SessionName=attrs.get('SessionName') or 'default',
            UserName=attrs.get('UserName') or '',
            FontSize=attrs.get('FontSize') or '12',
            Port=attrs.get('Port') or '23',
            Host=attrs.get('Host') or '',
        )
    writer.write(content.replace('/', '\\'))


def write_head(index, full_path, root_dir, writer):
    directory = full_path.replace(root_dir, '').strip('\\')
    if index == 0:
        name = 'Bookmarks'
    else:
        name = f'Bookmarks_{index}'
    writer.write(('\n\n[{BookMarks}]\n'
                  'SubRep={Directory}\n'
                  'ImgNum=42\n').format(BookMarks=name, Directory=directory))


file_map = {}


def generate_mobaxterm_sessions(xshell_session_path, deep):
    file_map[xshell_session_path] = []
    sub_files = os.listdir(xshell_session_path)
    for sub_file in sub_files:
        if sub_file.startswith('.'):
            continue
        full_path = os.path.join(xshell_session_path, sub_file)
        if os.path.isdir(full_path):
            generate_mobaxterm_sessions(full_path, deep + 1)
        else:
            if full_path.endswith('.xsh'):
                file_map[xshell_session_path].append(full_path)


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Usage: python xshell2moba.py <xshell_session_path>')
        exit(1)
    root_dir = sys.argv[1]
    generate_mobaxterm_sessions(root_dir, 0)
    index = 0
    with open("mobaxterm.mxtsessions", "w", encoding='gbk') as writer:
        for dir_name in file_map:
            write_head(index, dir_name, root_dir, writer)
            index = index + 1
            for file in file_map[dir_name]:
                write_body(file, writer)
